import datetime
import random
import uuid
from time import sleep
from PIL import Image
import requests
from io import BytesIO
from ddddocr import DdddOcr
import re

while True:
    try:
        response = requests.get('http://test.qamltech.com/verify-code.aspx')
        cookie_value1 = ''
        for key, value in response.cookies.items():
            cookie_value1 += key + '=' + value + ';'
        response.headers['Cookie'] = cookie_value1
        # print(cookie_value)
        img = Image.open(BytesIO(response.content))
        # img.show() # 显示图片
        img.save('./Appauto_Keyword/picture/1.png')
        ocr = DdddOcr()
        with open('./Appauto_Keyword/picture/1.png', 'rb') as f:
            img = f.read()
        res = ocr.classification(img)
        # print(res)

        url_admin = 'http://test.qamltech.com/do.ashx?$m=login'
        head_admin = {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'Cookie': f'{cookie_value1}'}
        data_admin = {'account': 'admin', 'pwd': '147123qaml', 'v-code': f'{res}'}
        res_admin = requests.post(url_admin, data=data_admin, headers=head_admin)
        # print(ooo.json())
        if res_admin.json().get('success') != True:
            raise Exception('验证码错误')

        ###################
        mac = input('请输入你的设备\033[5;33m MAC的后6位 \033[0m后点击回车（无关大小写）：')

        url_check = 'http://test.qamltech.com/admin/ajax.ashx?$c=BurstDevice&$m=PageData&DeviceStatus='
        head_check = {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'Cookie': f'{cookie_value1}'}
        data_check = {'type': '', 'key': mac, 'page': '0', 'pageSize': '15'}
        res_check = requests.post(url_check, data=data_check, headers=head_check)

        pattern_id = re.compile(r'"Id":"(.*?)"')
        cx_result_id = pattern_id.search(res_check.text)
        cx_id = cx_result_id.group(1)
        # print(cx_id)

        pattern_code = re.compile(r'"Code":"(.*?)"')
        cx_result_code = pattern_code.search(res_check.text)
        cx_code = cx_result_code.group(1)
        # print(cx_code)

        #####################################

        response = requests.get('http://test.qamltech.com/verify-code.aspx')
        cookie_value = ''
        for key,value in response.cookies.items():
            cookie_value += key + '=' + value + ';'
        response.headers['Cookie'] = cookie_value
        # print(cookie_value)
        img = Image.open(BytesIO(response.content))
        # img.show() # 显示图片
        img.save('./Appauto_Keyword/picture/1.png')
        ocr = DdddOcr()
        with open('./Appauto_Keyword/picture/1.png', 'rb') as f:
            img = f.read()
        res = ocr.classification(img)
        # print(res)

        url = 'http://test.qamltech.com/do.ashx?$m=login'
        headers2 = {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8','Cookie':f'{cookie_value}'}
        # data = {'account': 'admin','pwd': '147123qaml','v-code': f'{res}'}
        data = {'account': '13988888881','pwd': '123456','v-code': f'{res}'}
        ooo  =  requests.post(url, data=data, headers=headers2)
        # print(ooo.json())
        if ooo.json().get('success') != True:
            raise Exception('验证码错误')

        #########################
        el = input('请选择你想输入的爆破项目，\033[5;33m请输入 1.贵安 或 2.大学城 或 3.杭州电子 \033[0m，再点击回车：')
        ele = input('请输入的预计爆破时间，\033[5;33m请输入 X天后 或 今天 \033[0m，再点击回车：')
        try:
            if ele == '今天':
                tt = 1
            else:
                tt = int(ele[:1])
        except:
            print('类型填写错误！请填写为 X天后或今天 ，现在预计起爆时间为今天')
            tt = 1
        # print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        # print(datetime.datetime.now().date())
        yth = (datetime.timedelta(days=1)+datetime.datetime.now()).strftime("%Y-%m-%d %H:%M:%S")
        sth = (datetime.timedelta(days=tt-1)+datetime.datetime.now()).strftime("%Y-%m-%d %H:%M:%S")
        # print(yth,sth)

        #######################
        ele1 = input('请输入的\033[5;33m 雷管编号 \033[0m，再点击回车：')
        ele2 = input('请输入的雷管\033[5;33m 数量 \033[0m，再点击回车：')

        yscd = len(ele1[-5:])
        lx = 1
        lis = []
        lis.append('{"TubeNO":"%s","Status":2,"$$hashKey":"object:%d"}'%(ele1,random.randint(10000, 99999)))
        while lx <= int(ele2) - 1:
            cbh = int(ele1[-5:]) + int(lx)
            if cbh <= 99999:
                if len(str(cbh)) != yscd:
                    ncbh = ele1[:-5] + (yscd - len(str(cbh))) * '0' + str(cbh)
                else:
                    ncbh = ele1[:-5] + str(cbh)
            else:
                print(f'雷管编号最大为{ele1[:-5]}99999，生成成功部分已可查看！！')
                break
            add = '{"TubeNO":"%s","Status":2,"$$hashKey":"object:%d"}'%(ncbh,random.randint(10000, 99999))
            lis.append(add)
            lx += 1
        # print(lis)
        list_str = '[' + ', '.join(map(str, lis)) + ']'
        # print(str(lis))

        wz = 'http://test.qamltech.com/admin/ajax.ashx?$c=DetonatorOrder&$m=SaveOrder'
        tou = {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8','Cookie':f'{cookie_value}'}
        if el == '贵安' or el == '1':
            sj = {'PlanDeliveryTime': yth,'selectedSrvList[0][name]': cx_code,
                  'selectedSrvList[0][value]': cx_id,'selectedSrvList[0][$$hashKey]': 'object:724',
                  'Count': ele2,'ProjectName': '贵安数字产业园测试','ProjectId': '202312271','PurchaseOrgId': 'B-026','LinkMan': '',
                  'Address': '贵州省安顺市平坝区翠柏路','BurstTime': (datetime.timedelta(days=tt-1,minutes=2)+datetime.datetime.now()).strftime("%Y-%m-%d %H:%M:%S"),
                  'cables': '[{"CableId":"%s","CableLength":2,"DetonatorConut":3,"Remarks":"","Gsms":%s,"$$hashKey":"object:531"}]'%(str(uuid.uuid4()),list_str),
                  'DeviceList': cx_id,'SaleOrgId': 'B-026'}
        elif el == '杭州电子' or el == '3':
            sj = {'PlanDeliveryTime': yth, 'selectedSrvList[0][name]': cx_code,
                  # 'selectedSrvList[0][value]': 'e9efd781-53aa-4cb1-b794-066fc773c6a4',
                  'selectedSrvList[0][value]': cx_id,
                  'selectedSrvList[0][$$hashKey]': 'object:793', 'Count': ele2,
                  'ProjectName': '杭州电子科技大学文一路项目',
                  'ProjectId': 'a47d0651-9d52-4a6f-80ac-5b3052954582', 'PurchaseOrgId': 'B-026', 'LinkMan': '',
                  'Address': '', 'BurstTime': (datetime.timedelta(days=tt-1,minutes=2)+datetime.datetime.now()).strftime("%Y-%m-%d %H:%M:%S"),
                  'cables': '[{"CableId":"%s","CableLength":2,"DetonatorConut":2,"Remarks":"","Gsms":%s,"$$hashKey":"object:610"}]' % (str(uuid.uuid4()), list_str),
                  'DeviceList': cx_id, 'SaleOrgId': 'B-026'}
        else:
            sj = {'PlanDeliveryTime': yth,'selectedSrvList[0][name]': cx_code,
                   'selectedSrvList[0][value]': cx_id,'selectedSrvList[0][$$hashKey]': 'object:734',
                   'Count': ele2,'ProjectName': '花溪大学城爆破测试','ProjectId': '9072a1d0-4817-4d64-b57b-a07747b31f05',
                   'PurchaseOrgId': 'B-026','LinkMan':'','Address': '贵州省贵阳市云岩区思贤路','BurstTime': (datetime.timedelta(days=tt-1,minutes=2)+datetime.datetime.now()).strftime("%Y-%m-%d %H:%M:%S"),
                   'cables': '[{"CableId":"%s","CableLength":2,"DetonatorConut":2,"Remarks":"","Gsms":%s,"$$hashKey":"object:551"}]'%(str(uuid.uuid4()),list_str),
                   'DeviceList': cx_id,'SaleOrgId': 'B-026'}
        # print(sj)
        jg = requests.post(wz, data=sj, headers=tou)
        # print(jg.json())


        wz1 = 'http://test.qamltech.com/admin/ajax.ashx?$c=DetonatorOrder&$m=SalesDistributionPageData'
        tou1 = {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8','Cookie':f'{cookie_value}'}
        sj1 = {'type': '','page': '0','pageSize': '1'}
        jg1 = requests.post(wz1, data=sj1, headers=tou1)
        # print(jg1.text)
        pattern = re.compile(r'"Id":"(.*?)"')
        cx_result = pattern.search(jg1.text)
        cxid = cx_result.group(1)
        # print(cxid)

        wz2 = 'http://test.qamltech.com/admin/ajax.ashx?$c=DetonatorOrder&$m=UdateOrderStatus'
        tou2 = {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8','Cookie':f'{cookie_value}'}
        sj2 = {'Id': cxid}
        jg2 = requests.post(wz2, data=sj2, headers=tou2)
        # print(jg2.json())

        wz3 = 'http://test.qamltech.com/admin/ajax.ashx?$c=burstApplyLog&$m=PageData_org'
        tou3 = {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8','Cookie':f'{cookie_value}'}
        sj3 = {'page': '0','pageSize': '1'}
        jg3 = requests.post(wz3, data=sj3, headers=tou3)
        pattern = re.compile(r'"VerifyCode":\b\d{6}\b')
        cx_result = pattern.search(jg3.text)
        cxid = cx_result.group(0)
        print('\033[91m授权配送成功，授权验证码为：\033[0m'+cxid[-6:])
        sleep(10)
        break
    except:
        print('由于二维码识别成功率原因，导致本次登录失败，请再次输入！！')
        quit()



